package com.shuoyue.ycgk.download;

import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import com.shuoyue.ycgk.utils.NOpenFiles;

import java.io.File;

public class DownloadReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            //下载完成跳转去安装apk
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, id);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            //处理 如果还未完成下载，用户点击Notification ，跳转到下载中心
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }
    }

    private static void installApk(Context context, long downloadApkId) {
        try {
            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            Intent paramIntent = new Intent("android.intent.action.VIEW");
            //获取当前下载id数据库游标
            Cursor cursor = dm.query(new DownloadManager.Query().setFilterById(new long[]{downloadApkId}));
            cursor.moveToFirst();
            //获取下载apk文件uri的列数
            int fileUriIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
            //获取下载apk文件uri
            String fileUri = cursor.getString(fileUriIdx);
            paramIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri;
            // 7.0+ 需要将file://的uri转换为更安全的content://,并且增加读取uri权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                String path = "";
                if (fileUri != null) {
                    path = Uri.parse(fileUri).getPath();
                }
                uri = FileProvider.getUriForFile(context, context.getPackageName() + ".sswl.provider", new File(path));
                paramIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //            //兼容8.0
                //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                //                if (!hasInstallPermission) {
                //                    startInstallPermissionSettingActivity(context);
                //                    return;
                //                }
                //            }
            } else {
                uri = Uri.parse(fileUri);
            }
            //设置打开apk格式文件
            paramIntent.setDataAndType(uri, "application/vnd.android.package-archive");
            // TODO 打开APK
//            //兼容8.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity(context);
                    return;
                }
            }
            NOpenFiles.openFile(context, new File(uri.getPath()));

        } catch (Exception e) {
            e.printStackTrace();
            openLocalDir(context);
        }
    }


    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @TargetApi(Build.VERSION_CODES.O)
    private static void startInstallPermissionSettingActivity(Context context) {
        //后面跟上包名，可以直接跳转到对应APP的未知来源权限设置界面。使用startActivityForResult 是为了在关闭设置界面之后，获取用户的操作结果，然后根据结果做其他处理
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.getPackageName()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private static void openLocalDir(Context context) {
        //调用系统文件管理器打开指定路径目录
        //获取到指定文件夹，这里为：/storage/emulated/0/Android/data/你的包	名/files/Download
        File file = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //7.0以上跳转系统文件需用FileProvider，参考链接：https://blog.csdn.net/growing_tree/article/details/71190741
        Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".sswl.provider", file);
        intent.setData(uri);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

}